package com.ztesoft.zsmart.zcm.dialing.util.scriptUtils;

import com.ztesoft.zsmart.zcm.dialing.util.OSUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 执行一个外部命令并返回执行结果
 * 
 * @author <br>
 * @version <br>
 * @CreateDate 2013-9-17 <br>
 * @since <br>
 */
public final class Command {

    /**
     * instance
     */
    private static Command instance = null;

    /**
     * Command <br>
     */
    private Command() {
        // TODO Auto-generated constructor stub
    }

    /**
     * getInstance <br>
     * 
     * @return <br>
     */
    public static Command getInstance() {
        if (instance == null) {
            instance = new Command();
        }
        return instance;
    }

    /**
     * <p>
     * Title: execCmd
     * </p>
     * <p>
     * Description: 执行一个命令，并将结果返回
     * </p>
     * 
     * @param cmd
     * @return
     */
    public static String execCmd(String cmd) {
        if (StringUtils.isBlank(cmd)) {
            return "";
        }
        Map<String, String> result = ShellExecutor.execute(addCommander(cmd), null);
        return result.get("normalInfo");
    }

    /**
     * 根据操作系统类型获取命令行解释器
     * 
     * @param cmd <br>
     * @return <br>
     */
    public static List<String> addCommander(String... cmd) {
        List<String> rslt = new ArrayList<String>();
        if (OSUtil.isWindows()) {
            rslt.add("cmd.exe");
            rslt.add("/c");
        }
        else if (OSUtil.isSun()) {
            rslt.add("bash");
            rslt.add("-c");
        }
        else {
            rslt.add("sh");
            rslt.add("-c");
        }
        List<String> cmdList = Arrays.asList(cmd);
        for (String cmdStr : cmdList) {
            rslt.add(cmdStr);
        }
        return rslt;
    }

}
